package com.shundr.shipper.cargo;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shundr.shipper.R;
import com.shundr.shipper.base.BaseFragment;
import com.shundr.shipper.cargo.http.CargoRequest;
import com.shundr.shipper.cargo.model.CargoTemplateInfo;
import com.shundr.shipper.cargo.model.DeliverCargoInfo;
import com.shundr.shipper.cargo.view.DialogCargoType;
import com.shundr.shipper.cargo.view.DialogCargoType.OnCargoTypeListener;
import com.shundr.shipper.cargo.view.DialogTemplateCargo;
import com.shundr.shipper.cargo.view.DialogTemplateCargo.OnSelectedListener;
import com.shundr.shipper.cargo.view.DialogUnitType;
import com.shundr.shipper.cargo.view.DialogUnitType.OnUnitTypeListener;
import com.shundr.shipper.common.model.AreaInfo;
import com.shundr.shipper.common.model.AttributeInfo;
import com.shundr.shipper.common.util.AttrUtil;
import com.shundr.shipper.common.util.EncryptionUtils;
import com.shundr.shipper.common.util.JsonUtil;
import com.shundr.shipper.common.util.PrefConstants;
import com.shundr.shipper.common.util.PrefUtils;
import com.shundr.shipper.common.util.ProgressDialogHelper;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.common.view.DialogAreaGrid;
import com.shundr.shipper.common.view.DialogAreaGrid.OnConfirmListener;
import com.shundr.shipper.common.view.DialogChoiceLength;
import com.shundr.shipper.common.view.DialogChoiceLength.OnSelectListener;
import com.shundr.shipper.common.view.DialogResendTime;
import com.shundr.shipper.common.view.DialogResendTime.AttributeItemClickListener;
import com.shundr.shipper.common.view.MyDatePickerDialog;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.util.LLogger;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.truck.view.DialogChoiceTruckType;
import com.shundr.shipper.truck.view.DialogChoiceTruckType.OnChoiceTypeListener;
import com.shundr.shipper.user.LoginActivity;
import com.shundr.shipper.user.util.UserListener;
import com.shundr.shipper.user.util.UserUtil;
/**
 * 
 * OftenRouteFragment
 * 
 * @author larry 2015-5-6 下午5:38:06 
 * @version 1.0.0
 *
 */
public class DeliverGoodsFragment extends BaseFragment implements OnClickListener, UserListener{
	
	private RelativeLayout mLayoutNoContent;
	private TextView tvNoContent;
	private ImageView ivHope;
	
	private RelativeLayout mLayoutDeliver;
	
	private LinearLayout mLayoutTotal;
	
	private EditText etContactor;
	private Button btnEndDate;
	private EditText etContactorMobile;
	private EditText etContactorPhone;
	private Button btnResendTimes;
	
	private DialogTemplateCargo mTemplateCargo;
	
	private List<DeliverCargoInfo> mList = new ArrayList<DeliverCargoInfo>();
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 100:
				
				break;
			case CargoRequest.SUBMIT_CARGO_SUCCESSED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, msg.obj.toString());
				new Timer().schedule(new TimerTask() {
					
					@Override
					public void run() {
						getActivity().setResult(888);
						getActivity().finish();
					}
				}, 600);
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(getActivity(), (String)msg.obj);
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_deliver_goods, null);
		initView(view);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {//
		super.onActivityCreated(savedInstanceState);
		UserUtil.mUserListeners.add(this);
		refresh();
	}

	private void initView(View view) {
		mLayoutNoContent = (RelativeLayout) view.findViewById(R.id.layout_no_content);
		tvNoContent = (TextView) view.findViewById(R.id.tv_no_content);
		ivHope=(ImageView)view.findViewById(R.id.iv_hope);
		ivHope.setImageResource(R.drawable.iv_no_login);
		ivHope.setOnClickListener(this);
		
		mLayoutDeliver = (RelativeLayout) view.findViewById(R.id.layout_deliver_goods);
		
		mLayoutTotal = (LinearLayout)view.findViewById(R.id.layout_cargo);
		mLayoutTotal.addView(initCargoView());
		if(mLayoutTotal.getChildCount() == 1){
			mLayoutTotal.getChildAt(0).findViewById(R.id.layout_delete).setVisibility(View.INVISIBLE);
		}
//		mLayoutTotal.addView(initCargoView());
		
		etContactor = (EditText)view.findViewById(R.id.et_contactor);
		etContactorMobile = (EditText)view.findViewById(R.id.et_contactor_mobile);
		etContactorPhone = (EditText)view.findViewById(R.id.et_contactor_phone);
		
		try {
			etContactor.setText(LContext.getUserInfo(mContext).getUserName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			etContactorMobile.setText(LContext.getUserInfo(mContext).getUserPhone());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		btnEndDate = (Button)view.findViewById(R.id.btn_end_date);
		btnEndDate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Calendar cal = Calendar.getInstance();
				MyDatePickerDialog end = new MyDatePickerDialog(mContext,
						new OnDateSetListener() {

							@Override
							public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
								btnEndDate.setText(year + "-" + StringUtil.getDateStr((monthOfYear + 1)) + "-" + StringUtil.getDateStr(dayOfMonth));
							}
						}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
				end.show();
				end.initView(true, true, true);
			}
		});
		btnResendTimes = (Button)view.findViewById(R.id.btn_resend_time);
		btnResendTimes.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				DialogResendTime resendTime = new DialogResendTime(mContext, new AttributeItemClickListener() {
					
					@Override
					public void onItemClick(AttributeInfo info) {
						btnResendTimes.setText(info.getName());
						btnResendTimes.setTag(info.getCode());
					}
				});
				resendTime.show(getFragmentManager(), "resendTime");
			}
		});
		
		mTemplateCargo = new DialogTemplateCargo(mContext,"常发货模板");
	}
	
	private View initCargoView() {
		final View view = LayoutInflater.from(mContext).inflate(R.layout.view_cargo_info, null);
		TextView tvNumber = (TextView) view.findViewById(R.id.tv_number);
		Button btnInsert = (Button) view.findViewById(R.id.btn_insert);
		LinearLayout layoutDelete = (LinearLayout) view.findViewById(R.id.layout_delete);
		LinearLayout layoutStart = (LinearLayout) view.findViewById(R.id.layout_start);
		LinearLayout layoutEnd = (LinearLayout) view.findViewById(R.id.layout_end);
		final TextView btnStart = (TextView) view.findViewById(R.id.btn_start);
		String srcPlace=PrefUtils.getPrefString(getActivity(), PrefConstants.SRC_PLACE, LContext.nullStr);
		String startCode=PrefUtils.getPrefString(getActivity(), PrefConstants.SRC_CODE,LContext.nullStr);
		if(!StringUtil.isNull(srcPlace)){
			btnStart.setText(srcPlace);
			btnStart.setTag(startCode);
		}
		final TextView btnEnd = (TextView) view.findViewById(R.id.btn_end);
		final Button btnCargoType = (Button) view.findViewById(R.id.btn_cargo_type);
		btnCargoType.setText("普货");
		btnCargoType.setTag(0);
		final EditText etCargoNumber = (EditText) view.findViewById(R.id.et_cargo_number);
		etCargoNumber.requestFocus();
		final Button btnCargoNumberType = (Button) view.findViewById(R.id.btn_cargo_number_type);
		btnCargoNumberType.setText("吨");
		btnCargoNumberType.setTag(1);
		final Button btnCarType = (Button) view.findViewById(R.id.btn_car_type);
		final Button btnCarLength = (Button) view.findViewById(R.id.btn_car_length);
		final EditText etCarNumber = (EditText) view.findViewById(R.id.et_car_number);
		final EditText etPrice = (EditText) view.findViewById(R.id.et_price);
		final Button btnPriceType = (Button) view.findViewById(R.id.btn_price_type);
		btnPriceType.setText("吨");
		btnPriceType.setTag(1);
		final EditText etRemark = (EditText) view.findViewById(R.id.et_remark);

		int totalNumber = mLayoutTotal.getChildCount();
		tvNumber.setText((totalNumber + 1) + "");

		btnInsert.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mTemplateCargo = new DialogTemplateCargo(mContext,"常发货模板");
				mTemplateCargo.setSelectedListener(new OnSelectedListener() {
					
					@Override
					public void onSelected(CargoTemplateInfo info) {
						try {
							btnStart.setText(info.getCargoSrcPlace() == null ? "" : info.getCargoSrcPlace());
							btnStart.setTag(info.getCargoSrcCode() == null ? "" : info.getCargoSrcCode());
							btnEnd.setText(info.getCargoDstPlace() == null ? "" : info.getCargoDstPlace());
							btnEnd.setTag(info.getCargoDstCode() == null ? "" : info.getCargoDstCode());
//							btnCargoType.setText(DialogCargoType.getNameByCode(info.getCargoCategory()));
							btnCargoType.setText(info.getCargoCategory());
							etCargoNumber.setText(info.getCargoAmount());
							btnCargoNumberType.setText(info.getCargoUnitName() == null ? "" : info.getCargoUnitName());
							btnCarType.setText(info.getCargoTruckType() == null ? "" : info.getCargoTruckType());
							btnCarType.setTag(info.getCargoTruckTypeCode() == null ? "" : info.getCargoTruckTypeCode());
//							btnCarLength.setText(DialogChoiceLength.getNameByCode(info.getCargoTruckLength()));
							if(!StringUtil.isNull(info.getCargoTruckLength())){
								btnCarLength.setText(info.getCargoTruckLength() + "米");
								btnCarLength.setTag(info.getCargoTruckLength());
							}
							etCarNumber.setText(info.getCargoTruckNum()  == null ? "" : info.getCargoTruckNum());
							etPrice.setText(info.getCargoUnitPrice() == null ? "" : info.getCargoUnitPrice());
							btnPriceType.setText(info.getCargoPriceUnitName() == null ? "" : info.getCargoPriceUnitName());
							etRemark.setText(info.getCargoRemarks() == null ? "" : info.getCargoRemarks());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				mTemplateCargo.show();
			}
		});
		layoutDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mLayoutTotal.removeView(view);
			}
		});
		layoutStart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DialogAreaGrid area = new DialogAreaGrid(mContext, "发货地");
				area.setConfirmListener(new OnConfirmListener() {
					
					@Override
					public void onConfirm(String json) {
						try {
							List<AreaInfo> areas = JsonUtil.getList(json, AreaInfo.class);
							if(areas.size() > 0){
								btnStart.setText(areas.get(0).getName());
								btnStart.setTag(areas.get(0).getCode());
							}
						} catch (Exception e) {
							e.printStackTrace();
						}						
					}
				});
				area.show();
			}
		});
		layoutEnd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DialogAreaGrid area = new DialogAreaGrid(mContext, "收货地");
				area.setConfirmListener(new OnConfirmListener() {
					
					@Override
					public void onConfirm(String json) {
						try {
							List<AreaInfo> areas = JsonUtil.getList(json, AreaInfo.class);
							if(areas.size() > 0){
								btnEnd.setText(areas.get(0).getName());
								btnEnd.setTag(areas.get(0).getCode());
							}
						} catch (Exception e) {
							e.printStackTrace();
						}						
					}
				});
				area.show();
			}
		});
		btnCargoType.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DialogCargoType cargoType = new DialogCargoType(mContext, "货物类型", new OnCargoTypeListener() {
					
					@Override
					public void selected(AttributeInfo info) {
						btnCargoType.setText(info.getName());
						btnCargoType.setTag(info.getCode());
					}
				});
				cargoType.show();
			}
		});
		btnCargoNumberType.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) { 
				DialogUnitType unitType = new DialogUnitType(mContext, "单位", new OnUnitTypeListener() {
					
					@Override
					public void selected(AttributeInfo info) {
						btnCargoNumberType.setText(info.getName());
						btnCargoNumberType.setTag(info.getCode());
						btnPriceType.setText(info.getName());
						btnPriceType.setTag(info.getCode());
					}
				});
				unitType.show();
			}
		});
		btnCarType.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DialogChoiceTruckType choiceTruckType = new DialogChoiceTruckType(mContext, "选择车辆类型", AttrUtil.TYPE_TRUCK, new OnChoiceTypeListener() {
					
					@Override
					public void selected(AttributeInfo info) {
						try {
							btnCarType.setText(info.getName());
							btnCarType.setTag(info.getCode());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				choiceTruckType.show();
			}
		});
		btnCarLength.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DialogChoiceLength length = new DialogChoiceLength(mContext, "选择车辆长度", new OnSelectListener() {
					
					@Override
					public void selected(AttributeInfo info) {
						try {
							btnCarLength.setText(info.getName());
							btnCarLength.setTag(info.getCode());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				length.show();
			}
		});
		btnPriceType.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) { 
				DialogUnitType unitType = new DialogUnitType(mContext, "单位", new OnUnitTypeListener() {
					
					@Override
					public void selected(AttributeInfo info) {
						btnPriceType.setText(info.getName());
						btnPriceType.setTag(info.getCode());
					}
				});
				unitType.show();
			}
		});
		
		LinearLayout addCargo = (LinearLayout)view.findViewById(R.id.layout_add_cargo);
		addCargo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mLayoutTotal.addView(initCargoView());
			}
		});

		return view;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
		UserUtil.mUserListeners.remove(this);
		releaseImageView(ivHope);
	}

	@Override
	public void onResume() {
		super.onResume();
	}
	
	public void submit(){
		LLogger.e("发货了");
		if(initList()){//货源数据通过
			//检测公共信息
			if(checkCommon()){
				String json = JsonUtil.toJson(mList);
				String time = btnEndDate.getText().toString();
				if(!StringUtil.isNull(time)){
					time = time + " 00:00:00";
				}
				String name = etContactor.getText().toString();
				String mobile = etContactorMobile.getText().toString();
				String phone = etContactorPhone.getText().toString();
				String resend = btnResendTimes.getTag().toString();
				ProgressDialogHelper.show(mContext, "正在发货...");
				new CargoRequest(mContext, mHandler).submitCargo(json, time, name, mobile, phone,resend);//发货
			}
		}
	}
	
	private boolean initList() {
		boolean flag = true;
		for (int i = 0; i < mLayoutTotal.getChildCount(); i++) {
			View view = mLayoutTotal.getChildAt(i);
			if (checkView(view, i)) {
				DeliverCargoInfo info = new DeliverCargoInfo();
				TextView start = (TextView) view.findViewById(R.id.btn_start);//发货地
				info.setCargoSrcCode(start.getTag().toString());
				info.setCargoSrcPlace(start.getText().toString());
				TextView end = (TextView) view.findViewById(R.id.btn_end);//收货地
				info.setCargoDstCode(end.getTag().toString());
				info.setCargoDstPlace(end.getText().toString());
				Button cargoType = (Button) view.findViewById(R.id.btn_cargo_type);//货物类型
				info.setCargoCategory(cargoType.getText().toString());
				EditText cargoNumber = (EditText) view.findViewById(R.id.et_cargo_number);//货物数量
				info.setCargoAmount(cargoNumber.getText().toString());
				Button unit = (Button) view.findViewById(R.id.btn_cargo_number_type);//数量单位
				info.setCargoUnitName(unit.getText().toString());
				Button carType = (Button) view.findViewById(R.id.btn_car_type);//车辆类型
				info.setCargoTruckTypeCode(carType.getTag().toString());
				Button carLength = (Button) view.findViewById(R.id.btn_car_length);//车辆长度
				info.setCargoTruckLength(carLength.getTag().toString());
				EditText carNumber = (EditText) view.findViewById(R.id.et_car_number);//需车数量
				info.setCargoTruckNum(carNumber.getText().toString());
				EditText price = (EditText) view.findViewById(R.id.et_price);//价格
				info.setCargoUnitPrice(price.getText().toString());
				Button priceType = (Button) view.findViewById(R.id.btn_price_type);//价格单位
				info.setCargoPriceUnitName(priceType.getText().toString());
				EditText remark = (EditText) view.findViewById(R.id.et_remark);//备注
				info.setCargoRemarks(remark.getText().toString());
				CheckBox cbTTag = (CheckBox) view.findViewById(R.id.cb_ttag);//是否设为常发货
				if(cbTTag.isChecked()){
					String md5Id = "";
					String userId = "";
					if (LContext.userInfo != null)
						userId = LContext.userInfo.getUserId() + "";
					String md5Str = userId + info.getCargoCategory() + info.getCargoUnitName() + info.getCargoSrcCode() + info.getCargoDstCode() + info.getCargoTruckTypeCode()
							+ info.getCargoTruckLength() + info.getCargoRemarks();
					md5Id = EncryptionUtils.getMD5(md5Str);
					info.setMd5Id(md5Id);
					info.setTemplateTag("1");
				}else{
					info.setMd5Id("");
					info.setTemplateTag("0");
				}
				mList.add(info);
			} else {
				flag = false;
				break;
			}
		}
		return flag;
	}
	
	private boolean checkView(View view,int flag){
		String start = view.findViewById(R.id.btn_start).getTag().toString();
		if(StringUtil.isNull(start)){
			ToastHelper.toastShort(mContext, "请选择货源  " + (flag + 1) + " 的发货地");
			return false;
		}
		String end = view.findViewById(R.id.btn_end).getTag().toString();
		if(StringUtil.isNull(end)){
			ToastHelper.toastShort(mContext, "请选择货源  " + (flag + 1) + " 的收货地");
			return false;
		}
		String cargoType = view.findViewById(R.id.btn_cargo_type).getTag().toString();
		if(StringUtil.isNull(cargoType)){
			ToastHelper.toastShort(mContext, "请选择货源  " + (flag + 1) + " 的货物类型");
			return false;
		}
		
		EditText etCargoNumber = (EditText)view.findViewById(R.id.et_cargo_number);
		String cargoNumber = etCargoNumber.getText().toString();
		if(StringUtil.isNull(cargoNumber)){
			ToastHelper.toastShort(mContext, "请输入货源  " + (flag + 1) + " 的货物量");
			return false;
		}
		return true;
	}
	
	private boolean checkCommon(){
		if(StringUtil.isNull(etContactor.getText().toString())){
			ToastHelper.toastShort(mContext, "请输入联系人姓名");
			return false;
		}
		if(StringUtil.isNull(etContactorMobile.getText().toString())){
			ToastHelper.toastShort(mContext, "请输入联系电话");
			return false;
		}
		return true;
	}
	
	private void refresh(){
		try {
			if(LContext.isLogin()){
				mLayoutDeliver.setVisibility(View.VISIBLE);
				mLayoutNoContent.setVisibility(View.GONE);
			}else{
				tvNoContent.setText("您还未登录，点我登录");
				mLayoutNoContent.setVisibility(View.VISIBLE);
				mLayoutDeliver.setVisibility(View.GONE);
				ivHope.setImageResource(R.drawable.iv_no_login);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_no_content:
			if(!LContext.isLogin()){
				startActivity(new Intent(mContext, LoginActivity.class));
			}
			break;
		case R.id.iv_hope:
			if(!LContext.isLogin()){
				startActivity(new Intent(mContext, LoginActivity.class));
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onUserChanged(int flag) {
		refresh();
	}
	
}
